package com.friendar.webapp;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class for Servlet: FriendFinderServlet
 * 
 */
public class FriendFinderServlet extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;
	/**
	 * Error response string
	 */
	static final String errorResp = "<response><action>FriendFinder</action><status>Error"
			+ "</status><reason>XX</reason></response>";
	
	// this is the normal response
	static final String resp = "<response><action>FriendFinder></action><user>XX</user><status>OK</status>YY</response>";
	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public FriendFinderServlet() {
		super();
	}

	/*
	 * (non-Java-doc) This method returns an xml saying who are the friends
	 * within a specified radius
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Step 1: Parse the request for radius in metres and id of the user
		// looking for friends
		String userId, radius;
		long radii = 0;
		userId = request.getParameter("uid");
		radius = request.getParameter("radius"); // this should be in metres
		
		// set the content type to XML before anything is written back
		response.setContentType("application/xml");
		
		if ((userId == null) || (userId.isEmpty())) {

			sendErrorResponse("User ID is not valid", response);
			return;
		}
		ProfileHandler ph = ProfileHandler.getInstance();
		if(!ph.isValidUser(userId)) {
			// not a valid user id
			sendErrorResponse("User does not exist", response);
			return;
		}
		
		if ((radius == null) || (radius.isEmpty())) {
			// empty param do something
			sendErrorResponse("radius is not specified", response);
			return;
		}
		try {
			radii = Long.parseLong(radius);
		} catch (NumberFormatException e) {
			// the radius is not a valid number
			sendErrorResponse("Radius is not an number", response);
			return;
		}
		// Step 2: retrieve information from the database
		FriendFinder ff = new FriendFinder();
		ArrayList<FriendInfoDTO> fal = ff.getFriendDistances(userId, radii);
		
		// Step 3: Construct the XML
		StringBuffer friendsXML = new StringBuffer();
		for(int i=0; i<fal.size(); i++) {
			friendsXML.append(fal.get(i).toXML());
		}
		String respXML = resp.replaceAll("YY", friendsXML.toString());
		respXML = respXML.replaceAll("XX", userId);
		
		// Step 4: send the response
		response.getWriter().write(respXML);
		
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	/**
	 * Writes an error message back to the requester that the request was for some reason not valid
	 * @param reason Why the request was not valid
	 * @param resp response object where it needs to be written back
	 * @throws IOException
	 */
	private void sendErrorResponse(String reason, HttpServletResponse resp)
			throws IOException {
		resp.getWriter().write(errorResp.replaceAll("XX", reason));
	}
}